package ar.edu.uba.fi.jmit.graphvisualizer.client;

import java.util.List;

import ar.edu.uba.fi.jmit.graphvisualizer.shared.AlertInfo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class AlertListPanel extends VerticalPanel {

	private AlertServiceAsync alertService = GWT.create(AlertService.class);

	private FlexTable alertGrid;

	@Override
	protected void onLoad() {
		this.add(this.generateBodyPanel());
	}

	private Widget generateBodyPanel() {
		alertGrid = new FlexTable();
		Panel panel = new SimplePanel();
		panel.add(alertGrid);
		alertGrid.setBorderWidth(1);
		return panel;
	}

	public void update() {
		alertService.getLastReceivedAlerts(new AsyncCallback<List<AlertInfo>>() {

			@Override
			public void onSuccess(List<AlertInfo> alerts) {
				updateGrid(alerts);
				if (alerts.size()>0)
					setVisible(true);
			}

			@Override
			public void onFailure(Throwable alerts) {
				GWT.log("Failure AlertListPanel:update");

			}
		});
	}

	private void updateGrid(List<AlertInfo> alerts) {
		alertGrid.removeAllRows();
		for(AlertInfo alertInfo:alerts) {
			addRow(alertGrid, alertInfo);
		}
	}

	/**
	 * Add a row to the flex table.
	 */
	private void addRow(FlexTable flexTable, AlertInfo alertInfo) {
		int numRows = flexTable.getRowCount();
		flexTable.setText(numRows, 0, alertInfo.getAlertTime().toString());
		flexTable.setText(numRows, 1, alertInfo.getApplication());
		flexTable.setText(numRows, 2, alertInfo.getMonitor());
		flexTable.setText(numRows, 3, alertInfo.getSeverity());
		flexTable.setText(numRows, 4, alertInfo.getMessage());
//		flexTable.getFlexCellFormatter().setRowSpan(0, 1, numRows + 1);
	}

//	/**
//	 * Remove a row from the flex table.
//	 */
//	private void removeRow(FlexTable flexTable) {
//		int numRows = flexTable.getRowCount();
//		if (numRows > 1) {
//			flexTable.removeRow(numRows - 1);
//			flexTable.getFlexCellFormatter().setRowSpan(0, 1, numRows - 1);
//		}
//	}
}
